package com.platform.framework.controller.rights;

import java.security.MessageDigest;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.bean.Message;
import com.platform.common.utils.StringUtils;
import com.platform.framework.controller.BaseController;
import com.platform.framework.entity.rights.FwRightUser;
import com.platform.framework.service.rights.FwRightUserService;

@RestController
@RequestMapping("/users")
public class FwRightUsersController extends BaseController {


	
	@Autowired
	FwRightUserService fwRightUserService;
	
	
	/**
	 * 判断userCode是否可用,1表示可用，0表示不可用
	 * @param userCode
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "checkuser", method = { RequestMethod.GET, RequestMethod.POST })
	public String checkuser(HttpServletRequest request) throws Exception{
		
		String code = request.getParameter("code");//手机发的验证码
		String mobile = request.getParameter("mobile");//手机号码
		String userid = request.getParameter("userid");//用户code
		String email = request.getParameter("email");//邮箱
		String phone = request.getParameter("phone");
		String username =  request.getParameter("username");//用户姓名 ，根据传入的管养单位的名称来注册。
		if(StringUtils.isNotNull(userid) || StringUtils.isNotNull(email) || StringUtils.isNotNull(phone)) {
			String searchVal = "";
			if(StringUtils.isNotNull(userid)) {
				searchVal = userid;
			}else if(StringUtils.isNotNull(email)) {
				searchVal = email;
			}else if(StringUtils.isNotNull(phone)) {
				searchVal = phone;
			}
			
			String status = fwRightUserService.checkUser(searchVal);
			//1表示存在
			return status;
		}else if(StringUtils.isNotNull(username)) {//判断组织机构是否存在
			String status = fwRightUserService.checkUsername(username);
			//1表示存在
			return status;
		}else {//验证code和mobie   1表示通过
			return CheckCode.checkCode(mobile, code);
		}
	}
	
	@RequestMapping("/register")
 	public ModelAndView register(HttpServletRequest request) {
 		ModelAndView mv = new ModelAndView("rights/user/register");
 		return mv;
 	}
   /**
    * 
     * 描述：用户注册.
     * @author 王求卿[wangqiuqing] Tel18101037995
     * @param request
     * @return
 * @throws Exception 
    */
	@RequestMapping(value = "signup", method = { RequestMethod.POST })
	public String userSave(HttpServletRequest request) throws Exception{
		String data = request.getParameter("data");
		SignModel signModel =  JSONObject.parseObject(data, SignModel.class);
		
		FwRightUser  fwRightUser = new FwRightUser();
		fwRightUser.setOrgId(signModel.getOrgId());
		if("管理机构".equals(signModel.getOptionsRadiosinline())) {
			fwRightUser.setUserType("USERTYPE_GLJG");//管理机构
		}else {
			fwRightUser.setUserType("USERTYPE_KYDW");//科研单位
		}
		fwRightUser.setId(this.getUUID());
		fwRightUser.setCreateTime(new Date());
		fwRightUser.setCreateUserCode(signModel.getUserid());//操作code
		fwRightUser.setCreateUserName(signModel.getUsername());//姓名
		fwRightUser.setUserCode(signModel.getUserid());
		fwRightUser.setUserName(signModel.getUsername());
		fwRightUser.setIsDeleted("0");//未删除
		fwRightUser.setIsEnable("0");//刚注册的用户设置不可用
		fwRightUser.setRegTime(new Date());//注册时间
		String mobile = signModel.getPhone();
		fwRightUser.setTelephone(mobile);
		fwRightUser.setEmail(signModel.getEmail());
		fwRightUser.setPassword(signModel.getPassword().toUpperCase());
		
		String code = signModel.getVercode();//验证码
		
		if(!"1".equals(CheckCode.checkCode(mobile, code))) {
			return new Message(Message.ERROR, "非法的手机验证码!").toJson();
		}
		
		String status = fwRightUserService.checkUser(signModel.getUserid());
		if(!"0".equals(status)) {
			return new Message(Message.ERROR, "账号已存在!").toJson();
		}
		return fwRightUserService.signUser(fwRightUser);
	}
	
	/**
	 * 发送注册验证码
	 * @param request
	 * @param respose
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value="/sendcode/{mobile}")
	public String sendCode(HttpServletRequest request,@PathVariable String mobile) {
		SendCode send = new SendCode();
		return send.sendCode(mobile);
	}
	
	  @RequestMapping("/agreement")
	  public ModelAndView agreement() {
		 ModelAndView mv = new ModelAndView("rights/user/agreement");
		 return mv;
	  }
	
	
	/**
	 * 
	  * <p>功能描述：MD5加密。</p>	
	  * @param 原密码。
	  * @return MD5加密后密码。
	  * @since JDK1.6。
	  * <p>创建日期:2014-4-28 上午10:33:01。</p>
	  * <p>更新日期:[日期YYYY-MM-DD][更改人姓名][变更描述]。</p>
	 */
	public String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       

        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}